package com.wedo.mall.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import com.e.library.activity.EActivity;
import com.e.library.listener.EListener;
import com.e.library.utils.EViewUtils;
import com.e.library.widget.ETitleBar;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.hyphenate.easeui.map.GLocation;
import com.wedo.mall.R;
import com.wedo.mall.activity.agent.AgentDetailActivity;
import com.wedo.mall.activity.main.NearbyActivity;
import com.wedo.mall.adapter.AgentMapAdapter;
import com.wedo.mall.entity.Agent;
import com.wedo.mall.util.ParcelableTransaction;
import com.wedo.mall.util.WUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 谷歌地图
 * Created by e on 2017/7/4.
 */

public class MapActivity extends EActivity implements OnMapReadyCallback,GoogleMap.OnMarkerClickListener{

    public static void toMap(EActivity activity, List<Agent> list){
        Bundle bundle = new Bundle();
        //bundle.putParcelableArrayList("agents",new ArrayList<>(list));
        ParcelableTransaction.with().putParcelableList("agents",list);
        activity.toActivity(MapActivity.class,bundle);
    }

    public static void toMap(EActivity activity, List<Agent> list,String title){
        Bundle bundle = new Bundle();
        //bundle.putParcelableArrayList("agents",new ArrayList<>(list));
        ParcelableTransaction.with().putParcelableList("agents",list);
        bundle.putString("title",title);
        activity.toActivity(MapActivity.class,bundle);
    }

    @BindView(R.id.title_bar) ETitleBar title_bar;
    @BindView(R.id.rl_top) RelativeLayout rl_top;
    @BindView(R.id.rv_agents) RecyclerView rv_agents;

    private GoogleMap mMap;
    private List<Agent> agents;

    private GLocation gLocation;

    private ArrayMap<String,Marker> mMarker = new ArrayMap<>();

    @Override
    protected int layout() {
        return R.layout.activity_map;
    }

    @Override
    protected void onActivityCreated(Bundle state) {

        statusBar(R.color.map_title);

        String title = getIntent().getStringExtra("title");
        if(!TextUtils.isEmpty(title)) {
            title_bar.setTitle(R.string.nearby_title);
        }

        agents = ParcelableTransaction.with().getParcelableList("agents");
        //agents = getIntent().getParcelableArrayListExtra("agents");

        rv_agents.setHasFixedSize(true);
        EViewUtils.horizontal(rv_agents);
        AgentMapAdapter adapter = new AgentMapAdapter(this,agents);
        rv_agents.setAdapter(adapter);
        adapter.setItemClickListener(new EListener<Agent>() {
            @Override
            public void onInvoked(View view, Agent data, int position) {
                AgentDetailActivity.toDetail(MapActivity.this,data.id);
            }
        });

        gLocation = new GLocation(this){
            @Override
            protected void successful(double lng, double lat) {
                super.successful(lng, lat);
            }

            @Override
            protected void failure() {
                super.failure();
            }
        };

        gLocation.setZoom(15);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        title_bar.setOnForwardListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toActivity(NearbyActivity.class);
            }
        });
    }

    @OnClick(R.id.iv_map_close)
    protected void onCloseClick(){
        rl_top.setVisibility(View.GONE);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setOnMarkerClickListener(this);
        toMapMarker(agents);
        gLocation.onMapReady(mMap);
    }

    private void toMapMarker(List<Agent> list){
        mMap.clear();
        if (list == null || list.isEmpty()){
            return;
        }

        for (Agent agent:list){
            if (TextUtils.isEmpty(agent.latitude) || TextUtils.isEmpty(agent.longitude)){
                continue;
            }

            double lng = WUtils.toDouble(agent.longitude);
            double lat = WUtils.toDouble(agent.latitude);
            if (lng == 0 || lat == 0) {
                continue;
            }

            LatLng latLng = new LatLng(lat, lng);

            Marker marker = mMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_normal)));
            marker.setTag(agent);
            mMarker.put(agent.id, marker);
        }
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        for (Marker m:mMarker.values()){
            m.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_normal));
        }

        marker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.map_market_select));
        Object tag = marker.getTag();

        if(tag !=null && tag instanceof Agent) {
            rl_top.setVisibility(View.VISIBLE);
            Agent agent = (Agent)tag;
            int index = agents.indexOf(agent);
            rv_agents.scrollToPosition(index);
        }
        return true;
    }

    @Override
    public void onStart() {
        super.onStart();
        gLocation.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
        gLocation.onStop();
    }

    @Override
    public void onPause() {
        super.onPause();
        gLocation.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        gLocation.onResume();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        gLocation.onActivityResult(requestCode,resultCode,data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        gLocation.onRequestPermissionsResult(requestCode,permissions,grantResults);
    }
}
